package kr.co.redbean.loader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.text.Font;
	import flash.text.engine.FontMetrics;
	
	import kr.co.redbean.store.ObjectInfo;
	import kr.co.redbean.store.ObjectStore;

	public class BackgroundLoader
	{
		public function BackgroundLoader()
		{
		}
		
		public function load():void { trace('load background start');
			var os:ObjectStore = ObjectStore.getInstance();
			os.addEventListener(Event.COMPLETE, hnComplete);
			os.initADs();
			
			function hnComplete($e:Event):void { trace('ads setup');
				os.removeEventListener(Event.COMPLETE, hnComplete);
				doLoadObject(os);
			}
		}
		
		private function doLoadObject(os:ObjectStore, flag:int=0):void { trace('start background loading',flag);
			if(flag >= os.objectProxyList.length || os.objectProxyList[flag].onLoading === true) return;
			if(os.objectProxyList[flag].isLoaded === true ) doLoadObject(os,++flag);
			
			var obj:ObjectInfo;
			obj = os.objectProxyList[flag];trace(obj);
			
			var rootAD:ApplicationDomain;
			switch(obj.domain) {
				case 'member' : rootAD = os.adStore.memberAD;break;
				case 'menu' : rootAD = os.adStore.menuAD;break;
				case 'popup' : rootAD = os.adStore.popupAD;break;
				case 'assets' : rootAD = os.adStore.assetsAD;break;
			}
			trace(obj.domain);
			var ad:ApplicationDomain;
			var loader:Loader;
			
			ad = new ApplicationDomain(rootAD);
			
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, hnADLoaded);
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, hnADProgress);

			obj.onLoading = true;
			obj.loaderInfo = loader;
			
			loader.load(new URLRequest(obj.name+'.swf'), new LoaderContext( false , ad ));

			function hnADProgress($e:ProgressEvent):void {
				
			}
			function hnADLoaded($e:Event):void {
				$e.target.removeEventListener(Event.COMPLETE, hnADLoaded);
				trace(obj.name);
				obj.isLoaded = true;
				obj.loaderInfo = null;
				obj.objectProxy = new (ad.getDefinition(obj.name));
				obj.onLoading = false;
				
				doLoadObject(os,++flag);
			}
		}
	}
}